package com.efounder.chat.http;

import android.content.Context;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.common.BaseRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.chat.http.GetHttpUtil.FRIENDINITSTR;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;

/**
 * 星际通讯请求好友数据
 */
public class OpenPlanetFriendUserRequestUtil {

    public static final String TAG = "OpenPlanetFriendUserRequestUtil";

    //
    public static void getFriendData(final Context context, final GetHttpUtil.ReqCallBack callBack) {
        final List<User> users = new ArrayList<User>();
        final String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, EnvironmentVariable.getProperty("TalkChainUrl")
                        + "/tcserver/user/friendAddressList",
                params, new BaseRequestManager.ReqCodeCallBack<String>() {
                    @Override
                    public void onReqFailed(int errorCode, String errorMsg) {
                        ToastUtil.showToast(context, R.string.Network_error);
                        if (callBack != null) {
                            callBack.onReqFailed("fail");
                        }
                        //todo 针对区块链应用，如果errorcode =400 表示用户登录失效，需要重新登录 yqs
                        if (errorCode == 400 && EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                                .getString(R.string.special_appid))) {
                            //发送弹框提示用户
                            EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                        }
                    }

                    @Override
                    public void onReqSuccess(String result) {
                        try {
                            JSONObject resultObject = new JSONObject(result);
                            // 获取JSON
                            JSONArray jsonArray = resultObject.getJSONArray("addressList");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                // 解析JSON
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                                User user = new User();
                                user.setLoginUserId(Integer.valueOf(userid).intValue());
                                user.setId(jsonObject.getInt("imUserId"));
                                user.setName(jsonObject.getString("userId"));//手机号

                                if (jsonObject.has("nickName")) {
                                    user.setNickName(jsonObject.getString("nickName"));
                                } else {
                                    user.setNickName(jsonObject.getString("userName"));
                                }

                                if (jsonObject.has("sex")) {
                                    user.setSex(jsonObject.getString("sex"));
                                } else {
                                    user.setSex("M");
                                }
                                if (jsonObject.has("phone")) {
                                    user.setPhone(jsonObject.getString("phone"));
                                } else {
                                    user.setPhone("");
                                }
                                if (jsonObject.has("mobilePhone")) {
                                    user.setMobilePhone(jsonObject.getString("mobilePhone"));
                                } else {
                                    user.setMobilePhone("");
                                }
                                if (jsonObject.has("email")) {
                                    user.setEmail(jsonObject.getString("email"));
                                } else {
                                    user.setEmail("");
                                }
                                //好友类型
                                if (jsonObject.has("userType")) {
                                    user.setType(Integer.valueOf(jsonObject.getString("userType")));
                                } else {
                                    user.setType(User.PERSONALFRIEND);
                                }
                                if (jsonObject.has("avatar")) {
                                    if (!jsonObject.getString("avatar").equals("")
                                            && jsonObject.getString("avatar").contains("http")) {
                                        user.setAvatar(jsonObject.getString("avatar"));
                                    } else {
                                        user.setAvatar("");
                                    }
                                } else {
                                    user.setAvatar("");
                                }
                                if (jsonObject.has("note")) {//备注名
                                    user.setReMark(jsonObject.getString("note"));
                                } else {
                                    //user.setReMark(user.getNickName());
                                    user.setReMark("");
                                }
                                if (jsonObject.has("sign")) {//个性签名
                                    user.setSigNature(jsonObject.getString("sign"));
                                } else {
                                    user.setSigNature("");
                                }
                                user.setIsTop("1".equals(jsonObject.optString("isTop", "0")));
                                user.setIsBother("1".equals(jsonObject.optString("isBother", "0")));

                                user.setAllowStrangerChat(jsonObject.optInt("disableStrangers", 0) == 0 ? true : false);
                                //加密公钥
                                user.setRSAPublicKey(jsonObject.optString("comPublicKey"));

                                //钱包地址
                                String walletAddress = jsonObject.optString("ethAddress", "");
                                if (!walletAddress.toLowerCase().startsWith("0x")) {
                                    walletAddress = "0x" + walletAddress;
                                }
                                user.setWalletAddress(walletAddress);
                                //钱包公钥
                                user.setPublicKey(jsonObject.optString("ethPublicKey"));
                                user.setWeixinQrUrl(jsonObject.optString("weChatQRCode", user.getWeixinQrUrl()));
                                user.setZhifubaoQrUrl(jsonObject.optString("aliPayQRCode", user.getZhifubaoQrUrl()));
                                //星球
                                user.setPlanet(jsonObject.optString("planet", ""));
//                        user.setAllowStrangerChat(jsonObject.optInt("allowStranger", 1) == 1 ? true : false);
                                //  user.setReMark(null);//备注
                                user.setDeptId(0);
                                user.setIsImportantContacts(false);
                                users.add(user);
                            }
                            // 插入数据库
                            CommonThreadPoolUtils.execute(new Runnable() {
                                @Override
                                public void run() {
                                    WeChatDBManager.getInstance().insertOrUpdateUser(users);
                                    GetHttpUtil.changeInitState(FRIENDINITSTR);
                                }
                            });
                            if (callBack != null) {
                                callBack.onReqSuccess("success");
                            }
                            // 处理异常
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {

                    }
                });

    }
}
